/**
 * 
 */
package com.xinxi11.project.qx.filter;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.centfor.core.utils.CollectionUtils;
import com.centfor.core.utils.RegexValidateUtils;
import com.centfor.core.web.filter.utils.Log4jOperUtils;
import com.centfor.core.web.servlet.ServletUtils;

/**
 * 请在此加入你的功能说明
 * 
 * @author baobao
 * @date 2011-4-20
 */

public class FWLogFilter implements Filter {
	private static Log logger = LogFactory.getLog("fw");
	public static ThreadLocal<HttpSession> sessionLocal = new ThreadLocal<HttpSession>();
	private static List<String> ipList = null; // 允许String httpinvoke列表

	/*
	 * (non-Javadoc)
	 * 
	 * @see javax.servlet.Filter#destroy()
	 */
	@Override
	public void destroy() {
		// TODO Auto-generated method stub

	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see javax.servlet.Filter#doFilter(javax.servlet.ServletRequest,
	 * javax.servlet.ServletResponse, javax.servlet.FilterChain)
	 */
	@Override
	public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain chain) throws IOException, ServletException {
		HttpServletRequest req = (HttpServletRequest) request;
		HttpServletResponse res = (HttpServletResponse) response;

		String ip = ServletUtils.getClientAddress(req);
		String requestURL = req.getRequestURL().toString();
		String query = req.getQueryString();
		StringBuffer sb = new StringBuffer();
		HttpSession session = req.getSession(false);
		Object o_userName = null;
		Object o_userCode = null;

		String sessionId = null;
		if (session != null){
			sessionId = session.getId();
			o_userCode = session.getAttribute("cerp_session_userCode");
			o_userName = session.getAttribute("cerp_session_userName");
		}

		if (CollectionUtils.isNotNull(ipList)) {
			if (ipList.contains(ip)&&(requestURL.contains("/http/")||requestURL.contains("/sso/"))) {
				chain.doFilter(request, response);
				StringBuffer sblog = new StringBuffer();
				sblog.append("userCode==").append(o_userCode).append(",userName==").append(o_userName).append(
						",sessionID==" + sessionId + ",ip==").append(ip).append(
						",fwURL==").append(requestURL);
				logger.info(sblog);
				return;
			}
		}

		String[] noFomat = new String[] { ".js", ".css", ".gif", ".jpg",
				".swf", ".png" };

		if (RegexValidateUtils.validateUrl(requestURL, noFomat) == false) {

			chain.doFilter(request, response);
		} else {
			if (o_userCode == null) {
				
				if (((requestURL.endsWith("login.jsp")
						|| requestURL.endsWith("cerpCommUserAction.do") || requestURL
						.endsWith("resetPassword.html"))|| requestURL
						.endsWith("login.do")||requestURL.contains("/shipin/")) == false) {
					res.sendRedirect("login.jsp");
					return;
				}
			}
			String username = String.valueOf(o_userCode);
			sb.append("userCode==").append(username).append(",userName==").append(o_userName).append(
					",sessionID==" + sessionId + ",ip==").append(ip).append(
					",fwURL==").append(requestURL);

			sessionLocal.set(session);

			if (query != null) {
				sb.append("?").append(query);
			}
			//向log4j中的MDC中存值,配置文件可以获取值
			Log4jOperUtils.writeLog4j(req,res);
			logger.info(sb.toString());
			chain.doFilter(request, response);
		}
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see javax.servlet.Filter#init(javax.servlet.FilterConfig)
	 */
	@Override
	public void init(FilterConfig filterConfig) throws ServletException {
		ipList = new ArrayList<String>();
		String access_ip = filterConfig.getInitParameter("access_ip");
		if (StringUtils.isNotBlank(access_ip)) {
			String[] arr_ip = StringUtils.split(access_ip, ',');
			for (String ip : arr_ip) {
				ipList.add(ip);
			}
		}
	}
}
